//
//  CellFooterCollectionView.swift
//  MagicalCalendar
//
//  Created by CSS on 6/19/23.
//

import UIKit

class CellFooterCollectionView: UICollectionView {
    
    private var currentFooterViews: [Int:UICollectionReusableView] = [:]
    
    @objc public var nibName: String?
    @objc public var cellClass: AnyClass?
    @objc public var footerDelegate: CellFooterCollectionViewDelegate?

    override func layoutSubviews() {
        super.layoutSubviews()
        
        currentFooterViews.forEach({ $0.value.isHidden = true })
        
        if let flowlayout = collectionViewLayout as? CellFooterLayout {
            for missingAttribute in flowlayout.missingFooterAttributes {
                let footerView = footerView(atIndexPath: missingAttribute.indexPath)
                footerView.isHidden = false
                footerView.frame = missingAttribute.frame
                if subviews.count > 2 {
                    insertSubview(footerView, at: subviews.count - 2)
                } else {
                    addSubview(footerView)
                }
            }
        }
        
        
    }
    
    private func footerView(atIndexPath indexPath: IndexPath) -> UICollectionReusableView {
        if let footerView = currentFooterViews[indexPath.section] {
            footerDelegate?.footerWillReuse(atIndexPath: indexPath, reuseView: footerView, forCollectionView: self)
            return footerView
        }
        let footerView: UICollectionReusableView
        if let cellClass = cellClass as? UICollectionReusableView.Type {
            footerView = cellClass.init(frame: .zero)
        } else if let nibName = nibName {
            footerView = Bundle.main.loadNibNamed(nibName, owner: nil)?.first as! UICollectionReusableView
        } else {
            footerView = .init(frame: .zero)
        }
        currentFooterViews[indexPath.section] = footerView
        footerDelegate?.footerWillReuse(atIndexPath: indexPath, reuseView: footerView, forCollectionView: self)
        return footerView
    }
    
}

@objc protocol CellFooterCollectionViewDelegate: NSObjectProtocol {
    
    func footerWillReuse(atIndexPath indexPath: IndexPath, reuseView: UICollectionReusableView, forCollectionView: UICollectionView)
    
}
